package com.github.yoojia.mqtt.boot.plugins;

import com.github.yoojia.mqtt.MQTTSocket;
import com.github.yoojia.mqtt.Message;
import com.github.yoojia.mqtt.boot.Plugin;
import com.parkingwang.lang.data.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author Yoojia Chen (yoojiachen@gmail.com)
 * @since 1.0
 */
public class KeepAlivePlugin implements Plugin {

    public static final Logger LOGGER = LoggerFactory.getLogger(KeepAlivePlugin.class);

    public static final String TAG_FILTER = "keepalive";
    public static final int DEFAULT_PERIOD = 10 * 1000;

    private final AtomicInteger mPeriod = new AtomicInteger(DEFAULT_PERIOD); /*10s*/

    private final TimerTask mTimerTask = new TimerTask() {
        @Override
        public void run() {
            final MQTTSocket socket = mSocket.get();
            final Message event = socket.newPubMessageOfSelf("keep-alive".getBytes())
                    .builder()
                    .tag(TAG_FILTER)
                    .build();
            socket.send(event);
            LOGGER.debug("Send KeepAlive message...");
        }
    };

    private final AtomicReference<MQTTSocket> mSocket = new AtomicReference<>();

    private Timer mKeepAliveTimer;

    @Override
    public void onInit(MQTTSocket socket, Config config) {
        mPeriod.set(config.getInt("period", DEFAULT_PERIOD));
        mSocket.set(socket);
    }

    @Override
    public void onStart() {
        mKeepAliveTimer = new Timer("keep-alive-timer");
        mKeepAliveTimer.schedule(mTimerTask, 0, mPeriod.get());
    }

    @Override
    public void onStop() {
        mKeepAliveTimer.cancel();
    }

}
